const fs = require('fs-extra');
const path = require('path');
const csv = require('csv-parser');
const XLSX = require('xlsx');
const readline = require('readline');

/**
 * 解析文件中的手机号码
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array<string>>} 手机号码数组
 */
exports.parseFile = async (filePath) => {
  const ext = path.extname(filePath).toLowerCase();
  let phoneNumbers = [];
  
  try {
    switch (ext) {
      case '.csv':
        phoneNumbers = await parseCsv(filePath);
        break;
      case '.xlsx':
        phoneNumbers = await parseXlsx(filePath);
        break;
      case '.txt':
        phoneNumbers = await parseTxt(filePath);
        break;
      default:
        throw new Error(`不支持的文件格式: ${ext}`);
    }
    
    // 清洗手机号码并去重
    return cleanAndDeduplicatePhones(phoneNumbers);
  } catch (error) {
    console.error(`解析文件出错: ${error.message}`);
    throw error;
  }
};

/**
 * 合并文件分片
 * @param {string} chunkDir - 分片目录
 * @param {string} destPath - 目标文件路径
 * @param {number} totalChunks - 总分片数
 * @returns {Promise<void>}
 */
exports.mergeChunks = async (chunkDir, destPath, totalChunks) => {
  // 创建可写流
  const writeStream = fs.createWriteStream(destPath);
  
  for (let i = 0; i < totalChunks; i++) {
    const chunkPath = path.join(chunkDir, `${i}`);
    
    if (!await fs.pathExists(chunkPath)) {
      throw new Error(`分片 ${i} 不存在`);
    }
    
    // 读取分片并写入目标文件
    const chunkBuffer = await fs.readFile(chunkPath);
    await new Promise((resolve, reject) => {
      writeStream.write(chunkBuffer, (err) => {
        if (err) reject(err);
        else resolve();
      });
    });
    
    // 删除已合并的分片
    await fs.unlink(chunkPath);
  }
  
  // 完成写入
  await new Promise((resolve, reject) => {
    writeStream.end((err) => {
      if (err) reject(err);
      else resolve();
    });
  });
};

/**
 * 解析CSV文件
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array<string>>} 手机号码数组
 */
const parseCsv = async (filePath) => {
  return new Promise((resolve, reject) => {
    const phones = [];
    
    fs.createReadStream(filePath)
      .pipe(csv())
      .on('data', (data) => {
        // 提取所有字段的值
        Object.values(data).forEach(value => {
          if (value && typeof value === 'string') {
            phones.push(value.trim());
          }
        });
      })
      .on('end', () => resolve(phones))
      .on('error', reject);
  });
};

/**
 * 解析XLSX文件
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array<string>>} 手机号码数组
 */
const parseXlsx = async (filePath) => {
  const workbook = XLSX.readFile(filePath);
  const phones = [];
  
  // 遍历所有工作表
  for (const sheetName of workbook.SheetNames) {
    const worksheet = workbook.Sheets[sheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    
    // 遍历所有单元格
    jsonData.forEach(row => {
      row.forEach(cell => {
        if (cell && typeof cell === 'string' || typeof cell === 'number') {
          phones.push(String(cell).trim());
        }
      });
    });
  }
  
  return phones;
};

/**
 * 解析TXT文件
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array<string>>} 手机号码数组
 */
const parseTxt = async (filePath) => {
  return new Promise((resolve, reject) => {
    const phones = [];
    const rl = readline.createInterface({
      input: fs.createReadStream(filePath),
      crlfDelay: Infinity
    });
    
    rl.on('line', (line) => {
      if (line.trim()) {
        phones.push(line.trim());
      }
    });
    
    rl.on('close', () => resolve(phones));
    rl.on('error', reject);
  });
};

/**
 * 清洗手机号码并去重
 * @param {Array<string>} phones - 原始手机号码数组
 * @returns {Array<string>} 清洗后的手机号码数组
 */
const cleanAndDeduplicatePhones = (phones) => {
  // 简单的清洗规则：移除所有非数字字符，然后尝试标准化格式
  const cleaned = phones.map(phone => {
    // 移除所有非数字字符
    let cleanedPhone = phone.replace(/\D/g, '');
    
    // 简单的国际格式处理（可根据实际需求扩展）
    if (cleanedPhone.startsWith('86')) {
      return `+${cleanedPhone}`;
    } else if (cleanedPhone.startsWith('91')) {
      return `+${cleanedPhone}`;
    } else if (cleanedPhone.length === 10 && /^[6-9]/.test(cleanedPhone)) {
      // 印度手机号
      return `+91${cleanedPhone}`;
    } else if (cleanedPhone.length === 11 && cleanedPhone.startsWith('1')) {
      // 中国手机号
      return `+86${cleanedPhone}`;
    }
    
    return cleanedPhone ? `+${cleanedPhone}` : null;
  }).filter(phone => phone !== null); // 过滤空值
  
  // 去重
  return [...new Set(cleaned)];
};
